package org.farm.utils;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.farm.pojo.SysUser;
import org.farm.pojo.SysUserToken;
import org.farm.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class CacheManager {
    private static final Logger logger = LoggerFactory.getLogger(CacheManager.class);

    private final Cache<String, SysUser> userCache;
    private final Cache<String, SysUserToken> tokenCache;

    public CacheManager() {
        userCache = CacheBuilder.newBuilder()
                .maximumSize(1000)
                .expireAfterWrite(24, TimeUnit.HOURS)
                .build();

        tokenCache = CacheBuilder.newBuilder()
                .maximumSize(1000)
                .expireAfterWrite(24, TimeUnit.HOURS)
                .build();
    }

    public SysUser getUserFromCache(String username, SysUserService userService) {
        SysUser cachedUser = userCache.getIfPresent(username);
        if (cachedUser != null) {
            logger.debug("缓存命中，用户: {}", username);
            return cachedUser;
        }
        logger.debug("缓存未命中，查询数据库，用户: {}", username);
        SysUser user = userService.getUserByUsername(username);
        if (user != null) {
            userCache.put(username, user);
            logger.debug("用户加入缓存: {}", username);
        }
        return user;
    }

    public SysUserToken getTokenFromCache(String token, SysUserService userService) {
        SysUserToken cachedToken = tokenCache.getIfPresent(token);
        if (cachedToken != null) {
            logger.debug("缓存命中，Token: {}", token);
            return cachedToken;
        }
        logger.debug("缓存未命中，查询数据库，Token: {}", token);
        SysUserToken userToken = userService.getTokenByToken(token);
        if (userToken != null) {
            tokenCache.put(token, userToken);
            logger.debug("Token加入缓存: {}", token);
        }
        return userToken;
    }

    public void invalidateUserCache(String username) {
        userCache.invalidate(username);
        logger.debug("用户缓存失效: {}", username);
    }

    public void invalidateTokenCache(String token) {
        tokenCache.invalidate(token);
        logger.debug("Token缓存失效: {}", token);
    }
}